package com.rongshu.view.userInfo.activity;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.rongshu.R;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.login.adapter.QuestionFeedbackAdapter;
import com.rongshu.view.login.contract.QuestionFeedbackView;
import com.rongshu.view.login.entity.PasswordLogin;
import com.rongshu.view.login.entity.PictureInfomation;
import com.rongshu.view.login.entity.QuestionFeedback;
import com.rongshu.view.login.entity.ReportClass;
import com.rongshu.view.login.entity.UpLoadImageResult;
import com.rongshu.view.login.presenter.QuestionFeedbackPrensenter;
import com.rongshu.view.userInfo.entity.UpLoadImage;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class ToReportActivity extends BaseActivity<QuestionFeedbackPrensenter> implements QuestionFeedbackView, QuestionFeedbackAdapter.OnNormalorImageClickListener {
    @BindView(R.id.txt_top_title)
    TextView txt_top_title;
    @BindView(R.id.txt_top_function)
    TextView txt_top_function;
    @BindView(R.id.iv_pornographic)
    ImageView iv_pornographic;
    @BindView(R.id.iv_ad)
    ImageView iv_ad;
    @BindView(R.id.iv_plagiarize)
    ImageView iv_plagiarize;
    @BindView(R.id.iv_others)
    ImageView iv_others;
    @BindView(R.id.edt_user_suggest)
    EditText edt_user_suggest;
    @BindView(R.id.edt_contact_style)
    EditText edt_contact_style;
    @BindView(R.id.txt_input_number)
    TextView txt_input_number;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    //boolean
    private boolean isPornographic, isAd, isPlagiarize, isOthers;
    //adapter
    private QuestionFeedbackAdapter mQuestionFeedbackAdapter = null;
    // adapter list
    private List<PictureInfomation> mPictureInfomation = null;
    //type
    private int type = -1;
    //position
    private int position = -1;
    //返回相册集合
    private List<LocalMedia> selectList = new ArrayList<>();
    //图片上传成功返回地址
    private List<UpLoadImageResult.ResponseBean.ImgBean> imgBeanList = null;
    //文章id
    private int article_id = 0;
    //type
    private int report_type = 1;
    //intent
    private Intent intent = null;
    //上传的图片图片集合
    private List<PictureInfomation> mUploadPictureInfomations = null;

    @Override
    protected int initLayout() {
        return R.layout.activity_to_report_view;
    }

    @Override
    protected void initView() {
        //presenter
        setPresenter(new QuestionFeedbackPrensenter(this), this);
        //intent
        intent = getIntent();
        if (intent != null) {
            article_id = intent.getIntExtra(Constant.INTENT_MESSAGE, 0);
            report_type = intent.getIntExtra(Constant.INTENT_TYPE, report_type);
        }
        //top
        txt_top_title.setText("举报");
        txt_top_function.setText("提交");
        txt_top_function.setVisibility(View.VISIBLE);
        //设置RecyclerView
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 5);
        mRecyclerView.setLayoutManager(gridLayoutManager);
        //list
        mPictureInfomation = new ArrayList<>();
        mPictureInfomation.add(new PictureInfomation(null, QuestionFeedbackAdapter.NORMAL));
        //adapter
        mQuestionFeedbackAdapter = new QuestionFeedbackAdapter(this);
        mQuestionFeedbackAdapter.setPictureInfomationList(mPictureInfomation);
        //set listener
        mQuestionFeedbackAdapter.setOnNormalorImageClickListener(this);
        //set RecyclerView
        mRecyclerView.setAdapter(mQuestionFeedbackAdapter);
        //pic list
        imgBeanList = new ArrayList<>();
    }

    @Override
    protected void initData() {
        edt_user_suggest.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                txt_input_number.setText(s.length() + "/200");
            }
        });
    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @OnClick({R.id.layout_back, R.id.layout_pornographic, R.id.layout_ad,
            R.id.layout_plagiarize, R.id.layout_others, R.id.txt_top_function})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_back:
                finish();
                break;
            case R.id.layout_pornographic://色情
                isAd = false;
                isPlagiarize = false;
                isOthers = false;
                isPornographic = true;
                selectType();
                break;
            case R.id.layout_ad://广告
                isPornographic = false;
                isPlagiarize = false;
                isOthers = false;
                isAd = true;
                selectType();
                break;
            case R.id.layout_plagiarize://抄袭
                isPornographic = false;
                isAd = false;
                isOthers = false;
                isPlagiarize = true;
                selectType();
                break;
            case R.id.layout_others://其他
                //重置
                isPornographic = false;
                isAd = false;
                isPlagiarize = false;
                isOthers = true;
                selectType();
                break;
            case R.id.txt_top_function://提交
                String user_suggest = edt_user_suggest.getText().toString().trim();
                if (!isPornographic && !isAd && !isPlagiarize && !isOthers) {
                    toast("请选择举报类型");
                    return;
                }

                if (TextUtils.isEmpty(user_suggest)) {
                    toast(getString(R.string.question_couple_must_not_empty));
                    return;
                }

                if (!getAdapterImage().isEmpty()) {
                    uploadImage(getAdapterImage());
                } else {
                    submitFeedback();
                }
                break;
        }
    }

    /**
     * 清空选择项，重新选择提交类型
     */
    private void selectType() {
        iv_pornographic.setImageResource(isPornographic ? R.drawable.green_checked : R.drawable.green_uncheck);
        iv_ad.setImageResource(isAd ? R.drawable.green_checked : R.drawable.green_uncheck);
        iv_plagiarize.setImageResource(isPlagiarize ? R.drawable.green_checked : R.drawable.green_uncheck);
        iv_others.setImageResource(isOthers ? R.drawable.green_checked : R.drawable.green_uncheck);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    selectList = PictureSelector.obtainMultipleResult(data);
                    //加载图片到view
                    updateAdapterData(selectList);
                    break;
            }
        }
    }

    /**
     * 更新adapter
     *
     * @param selectList
     */
    public void updateAdapterData(List<LocalMedia> selectList) {
        if (selectList == null) {
            return;
        }
        List<PictureInfomation> pictureInfomations = new ArrayList<>();
        List<PictureInfomation> adapterList = getAdapterImage();
        if (type == QuestionFeedbackAdapter.NORMAL) {
            for (LocalMedia localMedia : selectList) {
                pictureInfomations.add(new PictureInfomation(localMedia.getPath(), QuestionFeedbackAdapter.IMAGE));
            }
            if (adapterList != null) {
                if (adapterList.size() > 0) {
                    pictureInfomations.addAll(getAdapterImage());
                }
            }
            if ((pictureInfomations.size()) < 3) {
                pictureInfomations.add(new PictureInfomation(null, QuestionFeedbackAdapter.NORMAL));
            }
        } else if (type == QuestionFeedbackAdapter.IMAGE) {
            if (mQuestionFeedbackAdapter != null) {
                pictureInfomations = mQuestionFeedbackAdapter.getPictureInfomationList();
                for (int i = 0; i < pictureInfomations.size(); i++) {
                    if (this.position == i) {
                        pictureInfomations.get(position).setImage_path(selectList.get(0).getPath());
                    }
                }
            }
        }

        if (mQuestionFeedbackAdapter != null) {
            if (type == QuestionFeedbackAdapter.NORMAL) {
                this.mPictureInfomation.clear();
                this.mPictureInfomation = pictureInfomations;
                mQuestionFeedbackAdapter.setPictureInfomationList(mPictureInfomation);
            }
            mQuestionFeedbackAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 获取adapter是Image类型的
     */
    private List<PictureInfomation> getAdapterImage() {
        List<PictureInfomation> mPictureInfomations = new ArrayList<>();
        if (mQuestionFeedbackAdapter != null) {
            for (PictureInfomation p : mQuestionFeedbackAdapter.getPictureInfomationList()) {
                if (p.getImage_type() == QuestionFeedbackAdapter.IMAGE) {
                    mPictureInfomations.add(p);
                }
            }
        }
        return mPictureInfomations;
    }


    /**
     * 上传图片
     */
    private void uploadImage(List<PictureInfomation> pictureInfomations) {
        if (pictureInfomations == null) {
            return;
        }
        this.mUploadPictureInfomations = pictureInfomations;
        Map<String, RequestBody> bodyMap = new HashMap<>();
        if (!mUploadPictureInfomations.isEmpty()) {
            for (int i = 0; i < mUploadPictureInfomations.size(); i++) {
                File file = new File(mUploadPictureInfomations.get(i).getImage_path());
                bodyMap.put("file" + i + "\"; filename=\"" + file.getName(), RequestBody.create(MediaType.parse("image/png"), file));
            }
            //上传图片
            presenter.postUploadMoreFile(bodyMap);
        }
    }

    /**
     * 提交
     */
    private void submitFeedback() {
        //反馈内容，联系方式
        String user_suggest = edt_user_suggest.getText().toString().trim();
        String contact_style = edt_contact_style.getText().toString().trim();
        if (!isPornographic && !isAd && !isPlagiarize && !isOthers) {
            toast("请选择举报类型");
            return;
        }

        if (TextUtils.isEmpty(user_suggest)) {
            toast(getString(R.string.question_couple_must_not_empty));
            return;
        }

        int user_id = 0;
        //获取登录的userid
        PasswordLogin.ResponseBean userInfo = UserInfoUtils.getUserInfo();
        if (userInfo != null) {
            user_id = userInfo.getUser_id();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("type", report_type);//1反馈/2举报用户/3举报文章/4举报贴子
        map.put("user_id_to", article_id);
        map.put("reporttype", isPornographic ? 1 : isAd ? 2 : isPlagiarize ? 3 : isOthers ? 4 : 5); //被举报类型(1色情/2广告/3抄袭/4其他/5无)
        //list
        List<String> stringList = null;
        if (imgBeanList != null) {
            stringList = new ArrayList<>();
            for (UpLoadImageResult.ResponseBean.ImgBean imgBean : imgBeanList) {
                stringList.add(imgBean.getFilePath());
            }
        }
        //body
        ReportClass reportClass = new ReportClass();
        reportClass.setFeedback(user_suggest);
        reportClass.setMobile(contact_style);
        reportClass.setImg(stringList);
        presenter.postReportUser(
                (int) map.get("user_id"),
                (int) map.get("type"),
                (int) map.get("user_id_to"),
                (int) map.get("reporttype"),
                Common.encryptionSign(map),
                reportClass);
    }

    @Override
    public void onClick(int type, int position) {
        switch (type) {
            case QuestionFeedbackAdapter.NORMAL:
            case QuestionFeedbackAdapter.IMAGE:
                this.type = type;
                this.position = position;
                PictureSelector.create(ToReportActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .maxSelectNum(1)
                        .previewImage(true)
                        .isCamera(true)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
        }
    }

    /**
     * 上传图片回调
     *
     * @param upLoadImage
     */
    @Override
    public void uploadImageResult(UpLoadImage upLoadImage) {
        if (upLoadImage.getErrCode() == 0) {
            UpLoadImage.ResponseBean bean = upLoadImage.getResponse();
            if (bean != null) {
                List<String> picList = bean.getImgUrl();
                if (!picList.isEmpty()) {
                    for (String path : picList) {
                        UpLoadImageResult.ResponseBean.ImgBean imgBean = new UpLoadImageResult.ResponseBean.ImgBean();
                        imgBean.setFilePath(path);
                        imgBeanList.add(imgBean);
                    }

                    if (imgBeanList != null && mUploadPictureInfomations != null) {
                        if (imgBeanList.size() == mUploadPictureInfomations.size()) {
                            submitFeedback();
                        }
                    }
                }
            }
        } else {
            toast(upLoadImage.getErrMsg());
        }
    }

    /**
     * 提交回调
     *
     * @param questionFeedback
     */
    @Override
    public void onQuestionFeedback(QuestionFeedback questionFeedback) {
        if (questionFeedback.getErrCode() == 0) {
            toast("提交成功");
            clean();
            onBackPressed();
        } else {
            toast(questionFeedback.getErrMsg());
        }
    }

    //清空数据
    private void clean() {
        edt_user_suggest.setText("");
        edt_contact_style.setText("");
        isPornographic = false;
        isAd = false;
        isPlagiarize = false;
        isOthers = false;
        selectType();
        //清空相册
        List<PictureInfomation> pictureInfomations = new ArrayList<>();
        pictureInfomations.add(new PictureInfomation(null, QuestionFeedbackAdapter.NORMAL));
        if (mQuestionFeedbackAdapter != null) {
            this.mPictureInfomation.clear();
            this.mPictureInfomation = pictureInfomations;
            mQuestionFeedbackAdapter.setPictureInfomationList(mPictureInfomation);
            mQuestionFeedbackAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onBackPressed() {
        showKeyboard(false);
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PictureFileUtils.deleteCacheDirFile(this);
    }
}
